package com.wenzhoujie.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.wenzhoujie.BaseActivity;
import com.wenzhoujie.ConfirmOrderActivity;
import com.wenzhoujie.LoginNewActivity;
import com.wenzhoujie.ShopCartActivity;
import com.wenzhoujie.TuanDetailActivity;
import com.wenzhoujie.app.App;
import com.wenzhoujie.customview.AbSlidingPlayView;
import com.wenzhoujie.customview.SDSlidingFinishLayout;
import com.wenzhoujie.customview.AbSlidingPlayView.AbOnChangeListener;
import com.wenzhoujie.model.CartGoodsModel;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.GoodsdescActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.SDActivityUtil;
import com.wenzhoujie.utils.ViewInject;

public class TuanDetailFirstFragment extends BaseFragment implements
		OnClickListener {
	@ViewInject(id = R.id.frag_tuan_detail_first_spv_image)
	private AbSlidingPlayView mSpvImage = null;

	@ViewInject(id = R.id.frag_tuan_detail_first_tv_current_price)
	private TextView mTvCurrentPrice = null;

	@ViewInject(id = R.id.frag_tuan_detail_first_tv_original_price)
	private TextView mTvOriginalPrice = null;

	@ViewInject(id = R.id.frag_tuan_detail_first_btn_buy_goods)
	private Button mBtnBuyGoods = null;

	private GoodsdescActModel mGoodsModel = null;

	private SDSlidingFinishLayout mFinishLayout = null;

	public void setmGoodsModel(GoodsdescActModel mGoodsModel) {
		this.mGoodsModel = mGoodsModel;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.frag_tuan_detail_first,
				container, false);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init() {
		mTvOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		initAbSlidingPlayView();
		registeClick();
		bindDataByGoodsModel(mGoodsModel);
	}

	private void bindDataByGoodsModel(GoodsdescActModel goodsModel) {
		if (goodsModel != null) {
			bindGoodsImage(goodsModel.getBig_gallery());

			String curPriceFormat = goodsModel.getCur_price_format();
			String oriPriceFormat = goodsModel.getOri_price_format();

			SDViewBinder.setTextView(mTvCurrentPrice, curPriceFormat, "未找到");
			SDViewBinder.setTextView(mTvOriginalPrice, oriPriceFormat, "未找到");

		}
	}

	/**
	 * 绑定轮播图片
	 * 
	 * @param listUrl
	 */
	private void bindGoodsImage(List<String> listUrl) {
		if (listUrl != null && listUrl.size() > 0) {
			String url = null;
			for (int i = 0; i < listUrl.size(); i++) {
				url = listUrl.get(i);
				Activity activity = getActivity();
				ImageView ivAdv = new ImageView(activity);
				ivAdv.setScaleType(ScaleType.FIT_XY);
				mSpvImage.addView(ivAdv);
				if (i == 0) {
					SDViewBinder.setImageFillScreenWidthByScale(ivAdv,
							mSpvImage, url);
				} else {
					SDViewBinder.setImageView(ivAdv, url);
				}
			}
		}
	}

	private void initSDSlidingFinishLayoutData() {
		if (mFinishLayout == null) {
			BaseActivity baseActivity = getBaseActivity();
			if (baseActivity != null) {
				mFinishLayout = baseActivity.getSDSlidingFinishLayout();
			}
		}
	}

	private void initAbSlidingPlayView() {
		mSpvImage.setNavHorizontalGravity(Gravity.CENTER);
		mSpvImage.navLinearLayout.setPadding(15, 1, 15, SDViewUtil.dp2px(10));
		mSpvImage.setOnPageChangeListener(new AbOnChangeListener() {
			@Override
			public void onChange(int position) {
				initSDSlidingFinishLayoutData();
				if (position == 0) {
					if (mFinishLayout != null) {
						mFinishLayout.removeIgnoredView(mSpvImage);
					}
				} else {
					if (mFinishLayout != null) {
						mFinishLayout.addIgnoredView(mSpvImage);
					}
				}
			}
		});
	}

	private void registeClick() {
		mBtnBuyGoods.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.frag_tuan_detail_first_btn_buy_goods:
			clickBuyGoods();
			break;

		default:
			break;
		}
	}
	
	LocalUserModel user = null;
	private void clickBuyGoods() {
		Activity activity = getActivity();
		user=App.getApplication().getmLocalUser();
		if (user == null) {
			SDActivityUtil.startActivity(getActivity(), LoginNewActivity.class);
		} else {
			if (activity != null && activity instanceof TuanDetailActivity) {
				TuanDetailActivity tuanDetailActivity = (TuanDetailActivity) activity;
				TuanDetailSecondFragment fragSecond = tuanDetailActivity
						.getmFragSecond();
				if (fragSecond != null && fragSecond.ismIsCanBuy()) // 可以购买
				{
					// TODO 购买
					if (mGoodsModel != null) {
						CartGoodsModel cartGoodsModel = new CartGoodsModel();

						if (!cartGoodsModel.setGoods(mGoodsModel, true)) {
							final ScrollView scrollView = (ScrollView) getActivity()
									.findViewById(
											R.id.act_tuan_detail_ssv_scroll);
							final FrameLayout flAttr = (FrameLayout) getActivity()
									.findViewById(
											R.id.act_tuan_detail_fl_container_third);
							SDViewUtil.scrollToViewY(scrollView, flAttr, 200);
							return;
						}
						if (cartGoodsModel.isHas_cart()) // 商品可以加入购物车
						{
							App.getApplication().getListCartGoodsModel()
									.add(cartGoodsModel);
							addShopCart(cartGoodsModel);
							startActivity(new Intent(getActivity(),
									ShopCartActivity.class));
							// if (cartGoodsModel.getLimit_num_format_int() > 0)
							// {
							// App.getApplication().getListCartGoodsModel().add(cartGoodsModel);
							// startActivity(new Intent(getActivity(),
							// ShopCartActivity.class));
							// } else
							// {
							// SDToast.showToast("该商品的库存为0，不能购买。");
							// }
						} else {
							// TODO 跳转到订单确认界面
							Intent intent = new Intent(getActivity(),
									ConfirmOrderActivity.class);
							List<CartGoodsModel> listModel = new ArrayList<CartGoodsModel>();
							listModel.add(cartGoodsModel);
							intent.putExtra(
									ConfirmOrderActivity.EXTRA_LIST_CART_GOODS_MODEL,
									(Serializable) listModel);
							// if (cartGoodsModel.getLimit_num_format_int() > 0)
							// {
							// // TODO 跳转到订单确认界面
							// Intent intent = new Intent(getActivity(),
							// ConfirmOrderNewActivity.class);
							// List<CartGoodsModel> listModel = new
							// ArrayList<CartGoodsModel>();
							// listModel.add(cartGoodsModel);
							// intent.putExtra(ConfirmOrderNewActivity.EXTRA_LIST_CART_GOODS_MODEL,
							// (Serializable) listModel);
							// } else
							// {
							// SDToast.showToast("该商品的库存为0，不能购买。");
							// }
						}
					}
				} else {
					SDToast.showToast("已过期不能购买");
				}
			}
		}
	}

	// 添加购物车
	private void addShopCart(CartGoodsModel cartGoodsModel) {
		RequestModel model = new RequestModel();
		model.put("act", "cart");
		model.put("a", "add");
		model.put("deal_id", cartGoodsModel.getGoods_id());
		model.put("num", cartGoodsModel.getNum());
		//String [] s={};
		if (!cartGoodsModel.getAttr_id_a().equals("")) {
			model.put("attr", cartGoodsModel.getAttr_id_a());
		}
		if (!cartGoodsModel.getAttr_id_b().equals("")) {
			model.put("attr", cartGoodsModel.getAttr_id_b());
		}
		model.put("email", user.getUser_name());
		model.put("pwd", user.getUser_pwd());
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				//JSONObject json = JSON.parseObject(responseInfo.result);
				// Toast.makeText(getActivity(), json+"", 1).show();
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {

			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}
}